package com.hfi.ood.payroll.classification;

import com.hfi.ood.payroll.domain.Paycheck;
import com.hfi.ood.payroll.domain.PaymentClassification;
import com.hfi.ood.payroll.domain.SalesReceipt;
import lombok.Builder;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ChangLiang
 * @date 2020/5/19
 */
@Builder
public class CommissionedClassification implements PaymentClassification {

    /**
     * 底薪
     */
    private Money salary;

    /**
     * 每单的佣金
     */
    private Money rate;

    /**
     * 销售凭条
     */
    Map<Date, SalesReceipt> receiptMap;

    @Override
    public Money calculatePay(Paycheck paycheck) {
        Money commission = Money.of(CurrencyUnit.of("CNY"), 0);
        try {
            commission= Money.total(receiptMap.values().stream().filter(tc -> tc.getDate().before(paycheck.getPayPeriodEnd())
                    && tc.getDate().after(paycheck.getPayPeriodStart())).map(tc -> calculatePayForReceipt(tc)).collect(Collectors.toList()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return salary.plus(commission);
    }

    private Money calculatePayForReceipt(SalesReceipt tc) {
        return rate.multipliedBy(tc.getAmount());
    }
}
